package io.github.jsp.util.monitoring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CompletableFuture;

@Component
public class HttpUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    
    public HttpResponse get(String url, int timeoutMs) {
        HttpURLConnection connection = null;
        try {
            URL urlObj = new URL(url);
            connection = (HttpURLConnection) urlObj.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(timeoutMs);
            connection.setReadTimeout(timeoutMs);
            connection.setRequestProperty("User-Agent", "ServiceMonitor/1.0");
            
            long startTime = System.currentTimeMillis();
            int responseCode = connection.getResponseCode();
            long responseTime = System.currentTimeMillis() - startTime;
            
            StringBuilder response = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(
                            responseCode >= 200 && responseCode < 300 
                                ? connection.getInputStream() 
                                : connection.getErrorStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line).append("\n");
                }
            }
            
            return new HttpResponse(responseCode, response.toString().trim(), responseTime, true);
            
        } catch (Exception e) {
            logger.debug("HTTP请求失败: {} - {}", url, e.getMessage());
            return new HttpResponse(0, "Request failed: " + e.getMessage(), 0, false);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    
    public CompletableFuture<HttpResponse> getAsync(String url, int timeoutMs) {
        return CompletableFuture.supplyAsync(() -> {
            return get(url, timeoutMs);
        });
    }
    
    public boolean isHealthy(String url, int timeoutMs, String expectedResponse) {
        HttpResponse response = get(url, timeoutMs);
        
        if (!response.isSuccess()) {
            return false;
        }
        
        if (response.getStatusCode() < 200 || response.getStatusCode() >= 300) {
            return false;
        }
        
        if (expectedResponse != null && !response.getBody().contains(expectedResponse)) {
            return false;
        }
        
        return true;
    }
    
    public static class HttpResponse {
        private final int statusCode;
        private final String body;
        private final long responseTimeMs;
        private final boolean success;
        
        public HttpResponse(int statusCode, String body, long responseTimeMs, boolean success) {
            this.statusCode = statusCode;
            this.body = body;
            this.responseTimeMs = responseTimeMs;
            this.success = success;
        }
        
        public int getStatusCode() { return statusCode; }
        public String getBody() { return body; }
        public long getResponseTimeMs() { return responseTimeMs; }
        public boolean isSuccess() { return success; }
        
        public boolean isHealthy() {
            return success && statusCode >= 200 && statusCode < 300;
        }
        
        @Override
        public String toString() {
            return String.format("HttpResponse{status=%d, time=%dms, success=%s}", 
                statusCode, responseTimeMs, success);
        }
    }
}